package jsyf.oa.service.customerReport;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.customerReport.AllCustomerReportDao;
import jsyf.oa.dao.system.CheckDao;
import jsyf.oa.dao.system.DepartDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.facade.customerReport.AllCustomerReportFacade;
import jsyf.oa.service.report.reportCommon.ReportCommonMethodsAndConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by 92852 on 2018/8/11.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class AllCustomerReportService implements AllCustomerReportFacade {
    @Autowired
    private AllCustomerReportDao allCustomerReportDao;
    @Autowired
    private ReportCommonMethodsAndConstant common;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private DepartDao departDao;

    @Override
    public JSONObject getCustomersByUserIds(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userIds = jsonParams.getString("userIds");
        String key = jsonParams.getString("key");
        String isIntention = jsonParams.getString("isIntention");
        StringBuffer condition = new StringBuffer();
        if (StringUtils.isNotBlank(userIds) && StringUtils.isNotEmpty(userIds)) {
            condition.append("AND v_sys_user_2_customer.createUserId in('" + userIds + "')\n");
        }
        if (StringUtils.isNotBlank(key) && StringUtils.isNotEmpty(key)) {
            condition.append("AND (\n" +
                    "v_sys_user_2_customer.customerName LIKE '%" + key + "%'\n" +
                    "OR v_sys_user_2_customer.tel LIKE '%" + key + "%'\n" +
                    ")\n");
        }
        if (StringUtils.isNotBlank(isIntention) && StringUtils.isNotEmpty(isIntention)&&isIntention.equals("1")) {
            condition.append("AND v_sys_user_2_customer.intentionModel IS NOT NULL\n");
            condition.append("AND v_sys_user_2_customer.intentionModel NOT in('无','暂无')\n");
        }
        /*分页信息*/
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        List<JSONObject> list = allCustomerReportDao.getCustomersByUserIds(condition.toString(), requestPage, pageSize);
        int recordCount = allCustomerReportDao.getCountGroupCustomerList(condition.toString());
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", requestPage);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", list);
        return result;
    }

    @Override
    public List<JSONObject> getOutGroupByUserId(String userIds, String key,String isIntention) {
        StringBuffer condition = new StringBuffer();
        if (StringUtils.isNotBlank(userIds) && StringUtils.isNotEmpty(userIds)) {
            condition.append("AND v_sys_user_2_customer.createUserId in('" + userIds + "')\n");
        }
        if (StringUtils.isNotBlank(key) && StringUtils.isNotEmpty(key)) {
            condition.append("AND (\n" +
                    "v_sys_user_2_customer.customerName LIKE '%" + key + "%'\n" +
                    "OR v_sys_user_2_customer.tel LIKE '%" + key + "%'\n" +
                    ")\n");
        }
        if (StringUtils.isNotBlank(isIntention) && StringUtils.isNotEmpty(isIntention)&&isIntention.equals("1")) {
            condition.append("AND v_sys_user_2_customer.intentionModel IS NOT NULL\n");
            condition.append("AND v_sys_user_2_customer.intentionModel NOT in('无','暂无')\n");
        }
        List<JSONObject> list = allCustomerReportDao.getOutGroupByUserId(condition.toString());
        return list;
    }

    @Override
    public String updateCustomerCreateByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String regionIds = jsonParams.getString("regionIds");
        /*查询该区域对应的省市县*/
        List<JSONObject> provinces = allCustomerReportDao.getProvinceByRegion(regionIds);
        String provinceName = "";
        for (JSONObject json : provinces) {
            provinceName = json.getString("provinceName") + "','" + provinceName;
        }
        Integer in = allCustomerReportDao.updateCustomerCreateByUserId(userId, provinceName);
        if (in > 0) {
            return "true";
        } else {
            return "false";
        }
    }

    @Override
    public JSONObject updateProvinceById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String ids = jsonParams.getString("customerIds");
        String type = jsonParams.getString("type");
        String userIds = jsonParams.getString("userIds");
        String key = jsonParams.getString("key");
        String provinceName = jsonParams.getString("provinceName");
        String cityName = jsonParams.getString("cityName");
        String countyName = jsonParams.getString("countyName");
        String isCreate = jsonParams.getString("isCreate");
        String customerCreateUserId = jsonParams.getString("customerCreateUserId");
        Integer d = 0;
        String customerId = "";
        StringBuffer condition = new StringBuffer();
        if (StringUtils.isNotBlank(userIds) && StringUtils.isNotEmpty(userIds)) {
            condition.append("AND v_sys_user_2_customer.createUserId in(" + userIds + ")\n");
        }
        if (StringUtils.isNotBlank(key) && StringUtils.isNotEmpty(key)) {
            condition.append("AND (\n" +
                    "v_sys_user_2_customer.customerName LIKE '%" + key + "%'\n" +
                    "OR v_sys_user_2_customer.tel LIKE '%" + key + "%'\n" +
                    ")\n");
        }

        /*
        * type=true  全选
        * false    部分选择
        * */
            if (type.equals("true")) {
           //全选
                //获得所有客户记录的ID
                List<JSONObject> customerIdList = allCustomerReportDao.getCustomersByUserIdsNoPage(condition.toString());
                for (JSONObject json : customerIdList) {
                    customerId = json.getString("customerId") + "','" + customerId;
                }
                String customerIds = customerId.substring(0, customerId.length() - 2);
                if ("0".equals(isCreate)){
                    //修改客户所在地
                    d = allCustomerReportDao.updateProvinceById("'"+customerIds,provinceName, cityName, countyName);
                }else {
                    //修改客户创建人
                    d = allCustomerReportDao.updateCreateById("'"+customerIds,customerCreateUserId);
                }

            } else {
                //非全选
                if ("0".equals(isCreate)){
                    //修改客户所在地
                    d = allCustomerReportDao.updateProvinceByIdNoAll(ids, provinceName, cityName, countyName);
                }else {
                    //修改客户创建人
                    d = allCustomerReportDao.updateCreateById(ids,customerCreateUserId);
                }

            }
        JSONObject result = new JSONObject();

        if (d > 0) {
            result.put("records", "true");
        } else {
            result.put("records", "false");
        }
        return result;
    }

    @Override
    public JSONObject updateCreateUser(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String createUserId = jsonParams.getString("createUserId");
        List<JSONObject> ids=allCustomerReportDao.getCustomerIds(createUserId);
      String customerId="";
        for (JSONObject json : ids) {
            customerId = json.getString("customerId") + "','" + customerId;
        }
        String customerIds = customerId.substring(0, customerId.length() - 2);

       int d = allCustomerReportDao.updateCreateById("'"+customerIds,createUserId);
        JSONObject result = new JSONObject();
        if (d > 0) {
            result.put("records", "true");
        } else {
            result.put("records", "false");
        }
        return result;
    }

    class NewJSONObject extends JSONObject {
        @Override
        public boolean equals(Object obj) {
            if (this == obj) return true;//检测this 与 otherObject 是否引用同一个对象
            if (obj == null)//obj 是否为 null(很有必要 )
                return false;
            else if (getClass() != obj.getClass())//比较this 与 obj 是否属于同一个类
                return false;
            String thisId = this.getString("id");
            String objId = ((JSONObject) obj).getString("id");
            if (null != thisId && null != objId) {
                return thisId.equals(objId);
            } else {
                return false;
            }
        }

        @Override
        public int hashCode() {
            String thisName = this.getString("name");
            if (null != thisName) {
                return thisName.hashCode();
            } else {
                return 0;
            }
        }
    }

    @Override
    public List<JSONObject> reportDayTree(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        Set<NewJSONObject> listResult = new HashSet<>();
        List<JSONObject> listCompanies;
        List<JSONObject> listDeparts;
        List<JSONObject> listUsers;
        StringBuffer newUserIds = new StringBuffer();
        //StringBuffer departIds=new StringBuffer();
        //第一步 获取所有可以看到的人(包括已离职人员)
        String userIds = checkDao.getChilderByUserIdContainLeave(userId, false);
        //第二步 获取所有可以看到的人的信息
        listUsers = userDao.getViewJSONListByCondition(" AND reportFlag=0  AND(roleName='区域经理' OR v_sys_user.roleName='大区经理') AND id IN(" + userIds + ") " +
                "GROUP BY id ORDER BY companySortNo DESC,departSortNo DESC,roleSortNo DESC,jobState DESC,entryDate DESC", new Object[]{});
        //获取满足条件的所有区域经理的ID
        for (int i = 0; i < listUsers.size(); i++) {
            newUserIds.append("'" + listUsers.get(i).getString("id") + "',");
        }
        userIds = newUserIds.toString();
        if (!StringUtils.isBlank(userIds)){
            userIds = userIds.substring(0, userIds.length() - 1);
        }else{
            userIds="''";
        }
        //第三步 获取所有可以看到的人的公司、部门
        listDeparts = userDao.getDepartByUserIdContainLeave(userIds);
        listCompanies = userDao.getCompanyByUserId(userIds);
        List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
        //添加人员节点
        for (int j = 0; j < listUsers.size(); j++) {
            JSONObject userJSon = new JSONObject();
            JSONObject objUser = listUsers.get(j);
            if ("大区经理".equals(objUser.getString("roleName"))) {
                userJSon.put("name", objUser.getString("name") + "(" + "大区" + ")");
            } else {
                userJSon.put("name", objUser.getString("name"));
            }
            if (objUser.getInteger("jobState")==1){
                userJSon.put("jobState","1");
            }else {
                userJSon.put("jobState","0");
            }
            userJSon.put("id", objUser.getString("id"));
            userJSon.put("pId", objUser.getString("departId"));
            userJSon.put("type", "user");
            userJSon.put("isCustomerNull",objUser.getString("isCustomerNull"));
            jsonObjectList.add(userJSon);
        }
        //添加部门节点
        for (int i = 0; i < listDeparts.size(); i++) {
            NewJSONObject newJSONObject = new NewJSONObject();
            JSONObject objDepart = listDeparts.get(i);
            String departId = objDepart.getString("id");
            String parentId = objDepart.getString("parentId");
            String companyId = objDepart.getString("companyId");
            String sortNo = objDepart.getString("sortNo");
            newJSONObject.put("name", objDepart.getString("name"));
            newJSONObject.put("parentId", parentId);
            newJSONObject.put("companyId", companyId);
            newJSONObject.put("pId", companyId);
            newJSONObject.put("type", "depart");
            newJSONObject.put("dataId", departId);
            newJSONObject.put("id", departId);
            newJSONObject.put("isParent", true);
            newJSONObject.put("sortNo", sortNo);
            listResult.add(newJSONObject);
        }
        //根节点root
        JSONObject objRoot = new JSONObject();
        objRoot.put("id", "0");
        objRoot.put("name", "滚滚向前集团");
        objRoot.put("type", "root");
        objRoot.put("open", true);
        objRoot.put("isParent", true);
        jsonObjectList.add(objRoot);
        if (null != listResult || listResult.size() > 0) {
            for (JSONObject jsonObject : listResult) {
                jsonObjectList.add(jsonObject);
            }
        }
        //部门排序
        Comparator<JSONObject> comparator = new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject jsonObject1, JSONObject jsonObject2) {
                if (null == jsonObject1 || null == jsonObject2) {
                    return -2;
                }
                //根据部门的sortNo排序
                if (jsonObject1.getString("type").equals("depart") || jsonObject2.getString("type").equals("depart")) {
                    if (jsonObject1.getString("type").equals("depart") && jsonObject2.getString("type").equals("depart")) {
                        return Integer.parseInt(jsonObject1.getString("sortNo")) - Integer.parseInt(jsonObject2.getString("sortNo"));
                    } else {
                        return 100;
                    }
                } else {
                    return -2;
                }
            }
        };
        Collections.sort(jsonObjectList, comparator);
        //添加公司节点
        for (int i = 0; i < listCompanies.size(); i++) {
            JSONObject objCompany = listCompanies.get(i);//id,name,sortNo,
            String parentId = objCompany.getString("parentId");
            if ("0".equals(listCompanies.get(0).getString("parentId"))) {
                if (com.alibaba.dubbo.common.utils.StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                    objCompany.put("pId", "0");
                    objCompany.put("open", true);
                } else {
                    objCompany.put("pId", parentId);
                    objCompany.put("open", false);
                }
            } else {
                objCompany.put("pId", "0");
                objCompany.put("open", true);
            }
            objCompany.put("type", "company");
            objCompany.put("isParent", true);
            jsonObjectList.add(objCompany);
        }
        return jsonObjectList;
    }

}
